<template>
  <div style="position:relative;height:100%;">
    <Drawer title="编辑位号编码" :closable="false" v-model="drawerValue" width="600">
      <div>
        <Form
          ref="deviceForm"
          :model="deviceForm"
          :label-width="80"
          value="true"
          style="padding: 3px 60px"
        >
          <Form-item label="SIM卡号">{{deviceForm.sim}}</Form-item>
          <Form-item label="设备状态">{{deviceForm.devStatus ? "在线" : "离线"}}</Form-item>
          <Form-item label="电池电量">{{deviceForm.battery}}</Form-item>
          <Form-item label="信号强度">{{deviceForm.signalStrength}}</Form-item>
          <Form-item label="数据时间">{{deviceForm.dataTime}}</Form-item>
          <Form-item label="位号编码">
            <Row>
              <Col span="4">
                <Input v-model="deviceForm.code1"></Input>
              </Col>
              <Col span="1" style="text-align:center;line-height:32px;">-</Col>
              <Col span="4">
                <Input v-model="deviceForm.code2"></Input>
              </Col>
              <Col span="1" style="text-align:center;line-height:32px;">-</Col>
              <Col span="4">
                <Input v-model="deviceForm.code3"></Input>
              </Col>
            </Row>
          </Form-item>
          <Form-item label="安装路段">
            <Input v-model="deviceForm.installRoad" style="width:215px;"></Input>
          </Form-item>
          <FormItem>
            <Button type="primary" :loading="loading" @click="saveForm">提交</Button>
          </FormItem>
        </Form>
      </div>
    </Drawer>
    <div style="position:relative;" :style="{'height':mapHeight+'px'}">
      <div :class="fullScreenStatus ? 'map-wrap-full' : 'map-wrap'">
        <div id="eden-map" :class="fullScreenStatus ? 'map-full' : ''"></div>
      </div>
      <div class="operate-card" style="width:24rem">
        <h4>批量配置位号编码</h4>
        <Form
          ref="batchForm"
          :model="batchForm"
          :label-width="80"
          value="true"
          style="padding: 3px 60px"
        >
          <Form-item label="位号编码">
            <Row>
              <Col span="8">
                <Input v-model="batchForm.code1"></Input>
              </Col>
              <Col span="1" style="text-align:center;line-height:32px;">-</Col>
              <Col span="8">
                <Input v-model="batchForm.code2"></Input>
              </Col>
            </Row>
          </Form-item>
          <Form-item label="安装路段">
            <Input v-model="batchForm.installRoad" style="width:215px;"></Input>
          </Form-item>
          <FormItem>
            <Button type="warning" @click="drawFence">画围栏</Button>
            <Button type="primary" :loading="loading" @click="batchSetInstallCode">提交</Button>
          </FormItem>
        </Form>
      </div>
    </div>
  </div>
</template>
<script>
import AMap from "AMap";
import DEVICE_PNG from "./icon/device.png";
import { getRealTimeBarList } from "@/api/operate";
import { installDevice, batchInstallDevice } from "@/api/device";
var mousetool = null;
export default {
  mounted() {
    this.mapInit();
    this.getPoints();
    this.mapHeight =
      window.innerHeight - 150 < 300 ? 300 : window.innerHeight - 150;
    // 然后监听window的resize事件．在浏览器窗口变化时再设置下高度．
    const that = this;
    window.addEventListener("resize", function() {
      that.mapHeight =
        window.innerHeight - 150 < 300 ? 300 : window.innerHeight - 150;
    });
  },
  data() {
    return {
      mapHeight: 500,
      points: [],
      map: "",
      fullScreenStatus: false,
      MarkerClustererMarker: "",
      vMarkerClustererMarkers: [],
      vMarkerClustererStatus: true,
      deviceForm: {
        devId: "",
        sim: "",
        devStatus: "",
        battery: "",
        signalStrength: "",
        dataTime: "",
        installCode: "",
        code1: "",
        code2: "",
        code3: "",
        installRoad: ""
      },
      batchForm: {
        code1: "",
        code2: "",
        installRoad: ""
      },
      drawerValue: false,
      loading: false,
      firstPointDevId: 0,
      isBatchSet: false, //是否在批量配置
      polygonPoints: [], //围栏点坐标
      batchInstallCodeParams: []
    };
  },
  methods: {
    updateDatas(data) {
      this.$emit("sendData", data);
    },
    mapInit() {
      this.map = new AMap.Map("eden-map", {
        resizeEnable: true,
        center: [105, 34],
        zoom: 5,
        zooms: [3, 20],
        expandZoomRange: true,
        mapStyle: "amap://styles/fresh"
      });
      var vm = this;
      this.map.plugin(["AMap.MouseTool"], function() {
        //鼠标工具插件
        mousetool = new AMap.MouseTool(vm.map);
      });
    },
    markerClustererInit() {
      var points = this.points;
      if (points.length > 0) {
        const _this = this;
        for (let i = 0; i < points.length; i++) {
          let marker = new AMap.Marker({
            position: new AMap.LngLat(points[i].lng, points[i].lat),
            icon: DEVICE_PNG,
            offset: new AMap.Pixel(-15, -15),
            extData: points[i].devId,
            map: _this.map
          });
          var infoWindow = new AMap.InfoWindow({
            isCustom: true,
            offset: new AMap.Pixel(20, -30)
          });

          marker.content = i;
          marker.on("click", markerClick);
          function markerClick(e) {
            // 设置首个点
            _this.firstPointDevId = points[i].devId;
            if (_this.isBatchSet) {
              _this.$Message.success("首个设置成功");
            }
            //构建信息窗体中显示的内容
            var index = e.target.content;
            var device = points[index];

            //如果不存在位号编码
            if (!device.installCode) {
              var installCode = _this.deviceForm.installCode;
              _this.drawerValue = true;
              for (var key in device) {
                _this.deviceForm[key] = device[key];
              }
            }
            //实例化信息窗体
            var title = device.devName;
            var content = [];
            content.push(`<p ><span>sim卡号 :</span> ${device.sim}</p>`);
            content.push(
              `<p><span>设备状态 :</span> ${
                device.devStatus ? "在线" : "离线"
              }</p>`
            );
            content.push(
              `<p ><span>位号编码 :</span> ${device.installCode}</p>`
            );
            content.push(`<p ><span>电池电量 :</span> ${device.battery}%</p>`);
            content.push(
              `<p ><span>信号强度 :</span> ${device.signalStrength}</p>`
            );
            content.push(`<p ><span>数据时间 :</span> ${device.dataTime}</p>`);

            //构建自定义信息窗体
            function createInfoWindow(title, content) {
              var info = document.createElement("div");
              info.className = "custom-info input-card content-window-card";

              //可以通过下面的方式修改自定义窗体的宽高
              //info.style.width = "400px";
              // 定义顶部标题
              var top = document.createElement("div");
              var titleD = document.createElement("div");
              var closeX = document.createElement("img");
              top.className = "info-top";
              titleD.innerHTML = title;
              closeX.src = "https://webapi.amap.com/images/close2.gif";
              closeX.onclick = closeInfoWindow;

              top.appendChild(titleD);
              top.appendChild(closeX);
              info.appendChild(top);

              // 定义中部内容
              var middle = document.createElement("div");
              middle.className = "info-middle";
              middle.style.backgroundColor = "white";
              middle.innerHTML = content;
              info.appendChild(middle);

              // 定义底部内容
              var bottom = document.createElement("div");
              bottom.className = "info-bottom";
              bottom.style.position = "relative";
              bottom.style.top = "0px";
              bottom.style.margin = "0 auto";
              var sharp = document.createElement("img");
              sharp.src = "https://webapi.amap.com/images/sharp.png";
              bottom.appendChild(sharp);
              info.appendChild(bottom);
              return info;
            }

            //关闭信息窗体
            function closeInfoWindow() {
              _this.map.clearInfoWindow();
            }

            infoWindow.setContent(createInfoWindow(title, content.join("")));
            infoWindow.open(_this.map, e.target.getPosition());
          }
          _this.vMarkerClustererMarkers.push(marker);
        }
        // AMap.plugin(["AMap.MarkerClusterer"]);
        // AMap.plugin(["AMap.ToolBar", "AMap.MouseTool", "AMap.MarkerClusterer"]);
        AMap.plugin(
          ["AMap.ToolBar", "AMap.Scale", "AMap.OverView", "AMap.MapType"],
          function() {
            // 在图面添加工具条控件，工具条控件集成了缩放、平移、定位等功能按钮在内的组合控件
            _this.map.addControl(new AMap.ToolBar());

            // 在图面添加比例尺控件，展示地图在当前层级和纬度下的比例尺
            _this.map.addControl(new AMap.Scale());

            // 在图面添加鹰眼控件，在地图右下角显示地图的缩略图
            _this.map.addControl(new AMap.OverView({ isOpen: true }));

            // 在图面添加类别切换控件，实现默认图层与卫星图、实施交通图层之间切换的控制
            _this.map.addControl(new AMap.MapType());
          }
        );
        _this.map.setFitView();
      }
    },
    async getPoints() {
      let res = await getRealTimeBarList({});
      if (res.code == 0) {
        console.log(res);
        this.points = res.data;
        this.markerClustererInit();
      }
    },
    fullScreen() {
      this.fullScreenStatus = !this.fullScreenStatus;
    },
    locateMarker(lng, lat) {
      this.map.setZoomAndCenter(17, [lng, lat]);
    },
    async saveForm() {
      this.loading = true;
      let installCode =
        this.deviceForm.code1 +
        "-" +
        this.deviceForm.code2 +
        "-" +
        this.deviceForm.code3;
      let params = {
        sim: this.deviceForm.sim,
        installCode: installCode,
        code1: this.deviceForm.code1,
        code2: this.deviceForm.code2,
        code3: this.deviceForm.code3,
        installRoad: this.deviceForm.installRoad
      };

      try {
        let result = await installDevice(params);

        if (result.code == "0") {
          this.$Message.success("提交成功!");
        } else {
          this.$Message.error(result.msg);
        }
      } catch (e) {
        this.$Message.error("服务器异常，稍后再试");
      }
      this.loading = false;
    },
    drawFence() {
      this.isBatchSet = true; //开始批量设置位号编码
      let vm = this;
      var mapEvent = AMap.event.addListener(mousetool, "draw", function(e) {
        var drawObj = e.obj;
        var points = drawObj.getPath();
        var newpoints = [];
        points.forEach((item, index) => {
          vm.polygonPoints.push({ x: item.lat, y: item.lng });
        });
        mousetool.close(false);
        vm.$Message.info({
          content: "请从带配置设备选择一个启示点",
          duration: 10
        });
      });
      var polygonOverlays = this.map.getAllOverlays("polygon");
      this.map.remove(polygonOverlays);
      mousetool.polygon({
        strokeColor: "#FF33FF", //线颜色
        strokeWeight: 6, //线宽
        strokeOpacity: 0.2, //线透明度
        fillOpacity: 0.4, //填充透明度
        fillColor: "#1791fc" //填充色
      });
    },
    async batchSetInstallCode() {
      this.isBatchSet=false;
      var polygonOverlays = this.map.getAllOverlays("polygon");
      var path = polygonOverlays[0].getPath();
      var setPoints = [];
      var markers = this.map.getAllOverlays("marker");
      markers.forEach((item, index) => {
        var isPointInRing = AMap.GeometryUtil.isPointInRing(
          item.getPosition(),
          path
        );
        if (isPointInRing) {
          setPoints.push(item);
        }
      });
      var initalPoint = null;
      var vm = this;
      setPoints.forEach((item, index) => {
        if (item.getExtData() == vm.firstPointDevId) {
          initalPoint = item;
        }
      });
      this.batchInstallCodeParams.push({
        installCode: `${this.batchForm.code1}-${this.batchForm.code2}-001`,
        code1: this.batchForm.code1,
        code2: this.batchForm.code2,
        code3: "001",
        devId: initalPoint.getExtData(),
        installRoad: this.batchForm.installRoad
      });
      setPoints.splice(
        setPoints.findIndex(
          item => item.getExtData() === initalPoint.getExtData()
        ),
        1
      );
      if (setPoints.length > 1) {
        this.computedDistance(setPoints, initalPoint, 2);
      } else {
        var lastPoint = setPoints[0];
        this.batchInstallCodeParams.push({
          installCode: `${this.batchForm.code1}-${this.batchForm.code2}-002`,
          code1: this.batchForm.code1,
          code2: this.batchForm.code2,
          code3: "002",
          devId: lastPoint.getExtData(),
          installRoad: this.batchForm.installRoad
        });
      }
      let res = await batchInstallDevice(this.batchInstallCodeParams);
      if (res.code == 0) {
        this.$Message.success("配置成功!");
        this.getPoints();
      } else {
        this.$Message.error(res.msg);
      }
    },
    computedDistance(setPoints, initalPoint, installCodeIndex) {
      var shortDistance = 0;
      var nextPoint = null;
      setPoints.forEach((item, index) => {
        var distance = Math.round(
          initalPoint.getPosition().distance(item.getPosition())
        );
        if (index == 0) {
          shortDistance = distance;
          nextPoint = item;
        } else {
          if (distance < shortDistance) {
            shortDistance = distance;
            nextPoint = item;
          }
        }
      });
      var installCode3 = 0;
      if (installCodeIndex < 10) {
        installCode3 = "00" + installCodeIndex;
      } else if (installCodeIndex < 100) {
        installCode3 = "0" + installCodeIndex;
      } else {
        installCode3 = installCodeIndex;
      }
      var installCode =
        this.batchForm.code1 +
        this.batchInstallCodeParams.push({
          installCode: `${this.batchForm.code1}-${
            this.batchForm.code2
          }-${installCode3}`,
          code1: this.batchForm.code1,
          code2: this.batchForm.code2,
          code3: installCode3,
          devId: nextPoint.getExtData(),
          installRoad: this.batchForm.installRoad
        });
      setPoints.splice(
        setPoints.findIndex(
          item => item.getExtData() === nextPoint.getExtData()
        ),
        1
      );
      if (setPoints.length > 1) {
        this.computedDistance(setPoints, nextPoint, installCodeIndex + 1);
      } else {
        if (installCodeIndex + 1 < 10) {
          installCode3 = "00" + (installCodeIndex + 1);
        } else if (installCodeIndex + 1 < 100) {
          installCode3 = "0" + (installCodeIndex + 1);
        } else {
          installCode3 = installCodeIndex + 1;
        }
        var lastPoint = setPoints[0];
        this.batchInstallCodeParams.push({
          installCode: `${this.batchForm.code1}-${
            this.batchForm.code2
          }-${installCode3}`,
          code1: this.batchForm.code1,
          code2: this.batchForm.code2,
          code3: installCode3,
          devId: lastPoint.getExtData(),
          installRoad: this.batchForm.installRoad
        });
      }
    }
  }
};
</script>
<style>
.map-wrap {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  z-index: 110;
}
.map-wrap-full {
  position: fixed;
  width: 100% !important;
  height: 100% !important;
  z-index: 110;
  top: 0;
  left: 0;
}
.map-full {
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
}
.map-wrap #eden-map {
  width: 100%;
  height: 100%;
}
.map-operator {
  position: absolute;
  top: 10px;
  right: 10px;
  width: 200px;
  height: 85px;
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  justify-content: space-between;
}
.map-operator > div {
  position: relative;
  width: 52px;
  height: 52px;
  background-repeat: no-repeat;
  background-position: center center;
  background-size: 50px;
  cursor: pointer;
}
.map-operator .drawing {
  background-image: url("icon/draw.png");
  color: #fe6579;
}
.map-operator .submit {
  background-image: url("icon/submit.png");
  color: #a9ea0a;
}
.map-operator .clear {
  background-image: url("icon/clear.png");
  color: #b8c5cd;
}

.map-operator > div > div {
  position: absolute;
  width: 52px;
  height: 22px;
  line-height: 22px;
  left: 0;
  bottom: -22px;
  font-size: 14px;
}
.marker {
  position: absolute;
  top: -20px;
  right: -118px;
  color: #fff;
  padding: 4px 10px;
  box-shadow: 1px 1px 1px rgba(10, 10, 10, 0.2);
  white-space: nowrap;
  font-size: 12px;
  font-family: "";
  background-color: #25a5f7;
  border-radius: 3px;
}
.content-window-card {
  position: relative;
  box-shadow: none;
  bottom: 0;
  left: 0;
  width: auto;
  padding: 0;
}

.content-window-card p {
  line-height: 20px;
}
.content-window-card p span {
  float: left;
  width: 58px;
  color: #a1a1a1;
}
.custom-info {
  border: solid 1px silver;
}

div.info-top {
  position: relative;
  background: none repeat scroll 0 0 #09baf0;
  border-bottom: 1px solid #ccc;
  border-radius: 5px 5px 0 0;
}

div.info-top div {
  width: 100%;
  text-align: center;
  display: inline-block;
  color: #fff;
  font-size: 14px;
  font-weight: bold;
  line-height: 31px;
  padding: 0 10px;
}

div.info-top img {
  position: absolute;
  top: 10px;
  right: 10px;
  transition-duration: 0.25s;
}

div.info-top img:hover {
  box-shadow: 0px 0px 5px #000;
}

div.info-middle {
  font-size: 12px;
  padding: 10px 10px;
  line-height: 20px;
}

div.info-bottom {
  height: 0px;
  width: 100%;
  clear: both;
  text-align: center;
}
.operate-card {
  display: flex;
  flex-direction: column;
  min-width: 0;
  word-wrap: break-word;
  background-color: #fff;
  background-clip: border-box;
  border-radius: 0.25rem;
  width: 22rem;
  border-width: 0;
  border-radius: 0.4rem;
  box-shadow: 0 2px 6px 0 rgba(114, 124, 245, 0.5);
  position: fixed;
  bottom: 1rem;
  right: 1rem;
  -ms-flex: 1 1 auto;
  flex: 1 1 auto;
  padding: 0.75rem 1.25rem;
  z-index: 1000;
}
</style>
